package com.chinasolf.yygh.orders.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chinasoft.enums.RefundStatusEnum;
import com.chinasoft.model.order.OrderInfo;
import com.chinasoft.model.order.PaymentInfo;
import com.chinasoft.model.order.RefundInfo;
import com.chinasolf.exception.YyghException;
import com.chinasolf.yygh.orders.service.OrderInfoService;
import com.chinasolf.yygh.orders.service.PaymentInfoService;
import com.chinasolf.yygh.orders.service.RefundInfoService;
import com.chinasolf.yygh.orders.service.WeixinService;
import com.chinasolf.yygh.orders.utils.ConstantPropertiesUtils;
import com.chinasolf.yygh.orders.utils.HttpClient;
import com.github.wxpay.sdk.WXPayConstants;
import com.github.wxpay.sdk.WXPayUtil;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class WeixinServiceImpl implements WeixinService {
    @Autowired
    private OrderInfoService orderInfoService;
    @Autowired
    private PaymentInfoService paymentInfoService;
    @Autowired
    private RefundInfoService refundInfoService;
    //生成二维码
    @Override
    public Map<String, Object> createNative(Long orderId) {

        //1.根据orderid查询订单信息
        OrderInfo order = orderInfoService.getOrderInfo(orderId);
        //2.向支付记录表添加记录
        paymentInfoService.savePatymentInfo(order);

        //3.使用httpclient调用微信接口，返回微信支付二维码地址

        //3.1封装微信接口
        Map paramMap = new HashMap();

        paramMap.put("appid", ConstantPropertiesUtils.APPID);
        paramMap.put("mch_id", ConstantPropertiesUtils.PARTNER);
        paramMap.put("nonce_str", WXPayUtil.generateNonceStr());
        Date reserveDate = order.getReserveDate();
        String reserveDateString = new DateTime(reserveDate).toString("yyyy/MM/dd");
        String body = reserveDateString + "就诊"+ order.getDepname();
        paramMap.put("body", body);
        paramMap.put("out_trade_no", order.getOutTradeNo());
        //paramMap.put("total_fee", order.getAmount().multiply(new BigDecimal("100")).longValue()+"");
        paramMap.put("total_fee", "1");//为了测试
        paramMap.put("spbill_create_ip", "127.0.0.1");
        paramMap.put("notify_url", "http://guli.shop/api/order/weixinPay/weixinNotify");
        paramMap.put("trade_type", "NATIVE");

        try {
            //3.2使用httpclient请求微信接口，得到二维码信息
            //设置请求微信接口路径
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
            //设置传递参数，参数以xml格式，进行编码
            String xmlParam = WXPayUtil.generateSignedXml(paramMap, ConstantPropertiesUtils.PARTNERKEY);
            client.setXmlParam(xmlParam);
            //设置支持https请求
            client.setHttps(true);
            //发送请求
            client.post();

            //请求微信接口之后，返回数据
            String xml = client.getContent();
            System.out.println("xml" + xml);
            //xml转换map
            Map<String,String> resultMap = WXPayUtil.xmlToMap(xml);
            //4.把需要数据封装到map集合，返回
            Map<String,Object> map = new HashMap<>();

            map.put("orderId", orderId);
            map.put("totalFee", order.getAmount());
            map.put("resultCode", resultMap.get("result_code"));
            map.put("codeUrl", resultMap.get("code_url"));
            return map;
        } catch (Exception e) {
            e.printStackTrace();
        }
        throw new YyghException(20001,"支付二维码生成失败");
    }

    @Override
    public Map<String, String> queryWxPayStatus(Long orderId) {
        OrderInfo orderInfo = orderInfoService.getOrderInfo(orderId);
        //1、封装参数
        Map paramMap = new HashMap<>();
        paramMap.put("appid", ConstantPropertiesUtils.APPID);
        paramMap.put("mch_id", ConstantPropertiesUtils.PARTNER);
        paramMap.put("out_trade_no", orderInfo.getOutTradeNo());
        paramMap.put("nonce_str", WXPayUtil.generateNonceStr());
        //设置请求微信接口信息
        HttpClient client = null;
        try {
            client = new HttpClient("https://api.mch.weixin.qq.com/pay/orderquery");
            client.setXmlParam(WXPayUtil.generateSignedXml(paramMap, ConstantPropertiesUtils.PARTNERKEY));
            client.setHttps(true);
            client.post();
            //3、返回第三方的数据，转成Map
            String xml = client.getContent();
            System.out.println("查询支付状态返回xml" + xml);
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);
            //4、返回
            return resultMap;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    //微信退款
    @Override
    public boolean refund(Long orderId) {
        //微信退款有两个值 订单交易号out_trade_no

        //存储到了支付记录表中 trade_no查询订单支付状态的时候返回 transaction_id
        //1.根据orderId查询支付记录
        QueryWrapper<PaymentInfo> wrapperPayment = new QueryWrapper<>();
        wrapperPayment.eq("order_id",orderId);
        PaymentInfo paymentInfo = paymentInfoService.getOne(wrapperPayment);

        //2.向退款记录表添加记录（退款状态 退款中）
        RefundInfo refundInfo = refundInfoService.saveRefundInfo(paymentInfo);
        //3.调用微信接口进行微信退款
        //3.1封装微信退款接口需要参数
        Map<String,String> paramMap = new HashMap<>(8);
        paramMap.put("appid",ConstantPropertiesUtils.APPID);       //公众账号ID
        paramMap.put("mch_id",ConstantPropertiesUtils.PARTNER);   //商户编号
        paramMap.put("nonce_str",WXPayUtil.generateNonceStr());
        paramMap.put("transaction_id",paymentInfo.getTradeNo()); //微信订单号
        paramMap.put("out_trade_no",paymentInfo.getOutTradeNo()); //商户订单编号
        paramMap.put("out_refund_no","tk"+paymentInfo.getOutTradeNo()); //商户退款单号
        //       paramMap.put("total_fee",paymentInfoQuery.getTotalAmount().multiply(new BigDecimal("100")).longValue()+"");
        //       paramMap.put("refund_fee",paymentInfoQuery.getTotalAmount().multiply(new BigDecimal("100")).longValue()+"");
        //TODO 为了测试0,01
        paramMap.put("total_fee","1");
        paramMap.put("refund_fee","1");
        //3.2发送请求
        try {
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/secapi/pay/refund");
            String paramXml = WXPayUtil.generateSignedXml(paramMap,ConstantPropertiesUtils.PARTNERKEY);
            client.setXmlParam(paramXml);
            client.setHttps(true);
            //设置证书
            client.setCert(true);
            client.setCertPassword(ConstantPropertiesUtils.PARTNER);//证书密码
            //发送请求
            client.post();
            //返回结果
            String xml = client.getContent();
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);
            if (null != resultMap && WXPayConstants.SUCCESS.equalsIgnoreCase(resultMap.get("result_code"))) {
                refundInfo.setCallbackTime(new Date());
                refundInfo.setTradeNo(resultMap.get("refund_id"));
                refundInfo.setRefundStatus(RefundStatusEnum.REFUND.getStatus());
                refundInfo.setCallbackContent(JSONObject.toJSONString(resultMap));
                refundInfoService.updateById(refundInfo);
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //4.根据微信退款接口返回值判断
        //如果返回成功，更新退款记录表，退款状态，已经成功
        //返回true
        return false;
    }
}
